<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>业务管理 - 业务报表</title>
    <link rel="stylesheet" href="../../css/style.css">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script src="../../js/utils.js"></script>
    <script src="../../js/api.js"></script>
    <script type="module" src="../../js/components/navigation.js"></script>
</head>
<body>
    <div class="app-container">
        <header class="app-header">
            <div class="logo">员工管理系统</div>
            <div class="user-info">
                <span id="username-display"></span>
                <button id="logout-btn" class="btn btn-secondary">退出登录</button>
            </div>
        </header>

        <div class="app-body">
            <aside class="sidebar">
                <nav class="menu">
                    <ul>
                        <li><a href="#" class="menu-item active" data-target="welcome">欢迎页</a></li>
                        <li class="menu-group">
                            <a href="#" class="menu-item">员工管理</a>
                            <ul class="submenu">
                                <li><a href="../employee/list.html" class="submenu-item">员工列表</a></li>
                                <li><a href="../employee/add.html" class="submenu-item">添加员工</a></li>
                            </ul>
                        </li>
                        <li class="menu-group">
                            <a href="#" class="menu-item">业务管理</a>
                            <ul class="submenu">
                                <li><a href="../business/list.html" class="submenu-item">业务列表</a></li>
                                <li><a href="../business/create.html" class="submenu-item">创建业务</a></li>
                            </ul>
                        </li>
                        <li class="menu-group">
                            <a href="#" class="menu-item">薪酬管理</a>
                            <ul class="submenu">
                                <li><a href="../salary/overview.html" class="submenu-item">薪酬概览</a></li>
                                <li><a href="../salary/manage.html" class="submenu-item">薪酬管理</a></li>
                            </ul>
                        </li>
                        <li class="menu-group">
                            <a href="#" class="menu-item">系统设置</a>
                            <ul class="submenu">
                                <li><a href="../system/user.html" class="submenu-item">用户管理</a></li>
                                <li><a href="../system/profile.html" class="submenu-item">个人设置</a></li>
                            </ul>
                        </li>
                    </ul>
                </nav>
            </aside>

            <main class="content">
                <div class="report-container">
                    <h2 class="report-title">业务报表</h2>
                     
                    <div class="filter-bar">
                        <div class="filter-group">
                            <label for="date-range">日期范围:</label>
                            <select id="date-range">
                                <option value="today">今天</option>
                                <option value="week">本周</option>
                                <option value="month" selected>本月</option>
                                <option value="quarter">本季度</option>
                                <option value="year">本年</option>
                                <option value="custom">自定义</option>
                            </select>
                        </div>
                        <div class="filter-group" id="custom-date-range" style="display: none;">
                            <label for="start-date">开始日期:</label>
                            <input type="date" id="start-date">
                            <label for="end-date">结束日期:</label>
                            <input type="date" id="end-date">
                        </div>
                        <div class="filter-group">
                            <label for="status-filter">状态:</label>
                            <select id="status-filter">
                                <option value="all">全部</option>
                                <option value="未开始">未开始</option>
                                <option value="进行中">进行中</option>
                                <option value="已完成">已完成</option>
                                <option value="已暂停">已暂停</option>
                            </select>
                        </div>
                        <button id="apply-filter" class="btn btn-primary">应用筛选</button>
                        <button id="export-report" class="btn btn-secondary">导出报表</button>
                    </div>
                     
                    <div class="stats-cards">
                        <div class="card">
                            <div class="card-title">总业务数</div>
                            <div class="card-value" id="total-business">0</div>
                            <div class="card-change">+12.5% 较上月</div>
                        </div>
                        <div class="card">
                            <div class="card-title">总收入</div>
                            <div class="card-value" id="total-revenue">¥0.00</div>
                            <div class="card-change">+8.2% 较上月</div>
                        </div>
                        <div class="card">
                            <div class="card-title">完成率</div>
                            <div class="card-value" id="completion-rate">0%</div>
                            <div class="card-change">+3.1% 较上月</div>
                        </div>
                        <div class="card">
                            <div class="card-title">平均周期</div>
                            <div class="card-value" id="avg-duration">0 天</div>
                            <div class="card-change">-2.3% 较上月</div>
                        </div>
                    </div>
                     
                    <div class="charts-container">
                        <div class="chart-item">
                            <h3>业务类型分布</h3>
                            <canvas id="business-type-chart"></canvas>
                        </div>
                        <div class="chart-item">
                            <h3>月度收入趋势</h3>
                            <canvas id="monthly-revenue-chart"></canvas>
                        </div>
                    </div>
                     
                    <div class="table-container">
                        <h3>业务列表</h3>
                        <table class="data-table">
                            <thead>
                                <tr>
                                    <th>业务名称</th>
                                    <th>开始日期</th>
                                    <th>结束日期</th>
                                    <th>状态</th>
                                    <th>收入</th>
                                    <th>负责人</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody id="business-table-body">
                                <!-- 数据将通过JavaScript动态加载 -->
                            </tbody>
                        </table>
                        <div class="pagination">
                            <button class="btn btn-secondary" id="prev-page">上一页</button>
                            <span id="page-info">第 1 页 / 共 0 页</span>
                            <button class="btn btn-secondary" id="next-page">下一页</button>
                        </div>
                    </div>
                </div>
            </main>
        </div>
    </div>

    <script>
        $(document).ready(function() {
            // 检查登录状态
            checkLoginStatus();

            // 显示用户名
            const username = localStorage.getItem('username');
            if (username) {
                $('#username-display').text(username);
            }

            // 退出登录
            $('#logout-btn').click(function() {
                localStorage.removeItem('token');
                localStorage.removeItem('username');
                window.location.href = '../../index.html';
            });

            // 日期范围选择器切换
            $('#date-range').change(function() {
                if ($(this).val() === 'custom') {
                    $('#custom-date-range').show();
                } else {
                    $('#custom-date-range').hide();
                }
            });

            // 应用筛选
            $('#apply-filter').click(function() {
                loadReportData();
            });

            // 导出报表
            $('#export-report').click(function() {
                alert('报表导出功能已触发，实际项目中会生成Excel/PDF文件');
            });

            // 分页按钮
            let currentPage = 1;
            const pageSize = 10;

            $('#prev-page').click(function() {
                if (currentPage > 1) {
                    currentPage--;
                    loadReportData();
                }
            });

            $('#next-page').click(function() {
                // 总页数将在加载数据后更新
                const totalPages = Math.ceil($('#total-business').text() / pageSize) || 1;
                if (currentPage < totalPages) {
                    currentPage++;
                    loadReportData();
                }
            });

            // 初始化加载报表数据
            loadReportData();

            function checkLoginStatus() {
                const token = localStorage.getItem('token');
                if (!token) {
                    window.location.href = '../../index.html';
                }
            }

            function loadReportData() {
                // 获取筛选条件
                const dateRange = $('#date-range').val();
                let startDate = '';
                let endDate = '';
                const status = $('#status-filter').val();

                if (dateRange === 'custom') {
                    startDate = $('#start-date').val();
                    endDate = $('#end-date').val();
                }

                // 调用API加载报表数据
                window.api.business.getReportData(dateRange, startDate, endDate, status, currentPage, pageSize)
                    .then(data => {
                        // 更新统计卡片
                        updateStatsCards(data.stats);

                        // 更新图表
                        updateCharts(data.charts);

                        // 更新表格数据
                        updateTableData(data.businesses);

                        // 更新分页信息
                        updatePagination(data.totalCount);
                    })
                    .catch(error => {
                        console.error('Failed to load report data:', error);
                        alert('加载报表数据失败，请重试');
                    });
            }

            function updateStatsCards(stats) {
                if (stats) {
                    $('#total-business').text(stats.totalBusiness || 0);
                    $('#total-revenue').text('¥' + (stats.totalRevenue || 0).toFixed(2));
                    $('#completion-rate').text((stats.completionRate || 0) + '%');
                    $('#avg-duration').text((stats.avgDuration || 0) + ' 天');
                }
            }

            function updateCharts(chartsData) {
                // 业务类型分布图表
                if (chartsData && chartsData.typeDistribution) {
                    const typeCtx = document.getElementById('business-type-chart').getContext('2d');
                    new Chart(typeCtx, {
                        type: 'pie',
                        data: {
                            labels: chartsData.typeDistribution.labels,
                            datasets: [{
                                data: chartsData.typeDistribution.values,
                                backgroundColor: [
                                    'rgba(255, 99, 132, 0.7)',
                                    'rgba(54, 162, 235, 0.7)',
                                    'rgba(255, 206, 86, 0.7)',
                                    'rgba(75, 192, 192, 0.7)',
                                    'rgba(153, 102, 255, 0.7)',
                                    'rgba(255, 159, 64, 0.7)'
                                ]
                            }]
                        },
                        options: {
                            responsive: true,
                            plugins: {
                                legend: {
                                    position: 'right'
                                }
                            }
                        }
                    });
                }

                // 月度收入趋势图表
                if (chartsData && chartsData.monthlyRevenue) {
                    const revenueCtx = document.getElementById('monthly-revenue-chart').getContext('2d');
                    new Chart(revenueCtx, {
                        type: 'bar',
                        data: {
                            labels: chartsData.monthlyRevenue.labels,
                            datasets: [{
                                label: '月度收入',
                                data: chartsData.monthlyRevenue.values,
                                backgroundColor: 'rgba(54, 162, 235, 0.7)'
                            }]
                        },
                        options: {
                            responsive: true,
                            scales: {
                                y: {
                                    beginAtZero: true,
                                    ticks: {
                                        callback: function(value) {
                                            return '¥' + value.toFixed(2);
                                        }
                                    }
                                }
                            }
                        }
                    });
                }
            }

            function updateTableData(businesses) {
                const tableBody = $('#business-table-body');
                tableBody.empty();

                if (businesses && businesses.length > 0) {
                    businesses.forEach(business => {
                        const row = $('<tr></tr>');
                        row.append(`<td>${business.name}</td>`);
                        row.append(`<td>${business.startDate}</td>`);
                        row.append(`<td>${business.endDate}</td>`);
                        row.append(`<td><span class="status-badge status-${business.status}">${business.status}</span></td>`);
                        row.append(`<td>¥${business.revenue.toFixed(2)}</td>`);
                        row.append(`<td>${business.owner}</td>`);
                        row.append(`<td>
                            <a href="update.html?id=${business.id}" class="btn btn-sm btn-primary">编辑</a>
                            <a href="#" class="btn btn-sm btn-secondary" onclick="viewBusiness(${business.id})">查看</a>
                        </td>`);
                        tableBody.append(row);
                    });
                } else {
                    tableBody.append('<tr><td colspan="7" class="no-data">暂无数据</td></tr>');
                }
            }

            function updatePagination(totalCount) {
                const totalPages = Math.ceil(totalCount / pageSize) || 1;
                $('#page-info').text(`第 ${currentPage} 页 / 共 ${totalPages} 页`);

                // 禁用/启用分页按钮
                if (currentPage === 1) {
                    $('#prev-page').prop('disabled', true);
                } else {
                    $('#prev-page').prop('disabled', false);
                }

                if (currentPage >= totalPages) {
                    $('#next-page').prop('disabled', true);
                } else {
                    $('#next-page').prop('disabled', false);
                }
            }

            // 全局函数用于查看业务详情
            window.viewBusiness = function(id) {
                // 在实际项目中，可能会跳转到详情页或显示模态框
                alert(`查看业务 ID: ${id}`);
            };
        });
    </script>
</body>
</html>